<?php

class Language_Exception extends CMS_Exception {}

class Language_Translation_Not_Set_Exception extends Language_Exception {}
class Language_Translation_Not_Found_Exception extends Language_Exception {}

class Language {

	protected $id;
	protected $name;
	protected $location;
	protected $site;

	protected static $translate = array();

	public static function GetDefault(){
		$lang = Site::GetInstance()->getValue('language');
		return Language::GetByID($lang);
	}

	public static function GetByID($id){
		$result = Database::getInstance()->query("SELECT * from `languages` WHERE `id` = %u AND `site` = %u", $id, Site::getInstance()->GetID());
		if(!($lang = $result->fetch_object('Language'))){
			throw new Language_Not_Found_Exception();
		}
		return $lang;
	}

	public static function setTranslation($k, $v){
		Language::$translate[trim($k,'/')] = $v;
	}
		
	public static function setTranslations($data, $prefix = ''){
		foreach($data as $k => $v){
			Language::setTranslation($prefix . '/' . $k, $v);
		}
	}

	public static function getTranslation($k){
		if(isset(Language::$translate[$k])){
			return Language::$translate[$k];
		}
		throw new Language_Translation_Not_Set_Exception();
	}

	public function translate($data){
		array_unshift($data, $this->location);
		try {
			return Language::getTranslation(join('/',$data));
		} catch(Exception $e){}
		$base = 'language/';
		$files = array();
		foreach($data as $add){
			$files[] = $base . $add;
			$base .= $add . '/';
		}
		$files = array_reverse($files);
		foreach($files as $file){
			try {
				$language = $this;
				CMS::File($file);
				unset($language);
				return Language::getTranslation(join('/',$data));
			} catch (Exception $e){
				unset($language);
			}
		}
		throw new Language_Translation_Not_Found_Exception();
	}

}
